package com.mazaiting.redeye.module.media

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.mazaiting.easy.app.IApplicationComponent
import com.mazaiting.easy.base.fragment.BaseLoadingFragment
import com.mazaiting.redeye.R
import com.mazaiting.redeye.base.ApplicationComponentImpl
import com.mazaiting.redeye.module.feed.WormFragment
import com.mazaiting.redeye.module.friend.FriendFragment

/**
 * 媒体碎片
 */
class MediaFragment : BaseLoadingFragment<MediaPresenter>(), MediaContract.View {
    /**
     * 标题列表
     */
    private val mTitles: MutableList<String> = mutableListOf()
    /**
     * 碎片列表
     */
    private val mFragments: MutableList<Fragment> = mutableListOf()
    /**
     * ViewPager 适配器
     */
    private var mAdapter: MediaViewPagerAdapter? = fragmentManager?.let { MediaViewPagerAdapter(it, mFragments, mTitles) }

    override fun bindView(view: View, savedInstanceState: Bundle?) {
        super.bindView(view, savedInstanceState)
        // 加载 TabLayout
        val tabLayout = view.findViewById<TabLayout>(R.id.media_tab_layout)
        // 加载 ViewPager
        val viewPager = view.findViewById<ViewPager>(R.id.media_view_pager)
        // 设置缓存页面
        viewPager?.offscreenPageLimit = 5
        // 设置适配器
        viewPager?.adapter = mAdapter
        // 关联 ViewPager
        tabLayout.setupWithViewPager(viewPager)
    }

    override fun lazyFetchData() {
        presenter?.loadMediaList()
    }

    override fun getContentLayout(): Int = R.layout.fragment_media

    override fun inject(applicationComponent: IApplicationComponent?) {
        DaggerMediaComponent
            .builder()
            .applicationComponentImpl(applicationComponent as ApplicationComponentImpl)
            .build()
            .inject(this)
    }

    override fun mediaListSuccess(data: List<String>) {
        mTitles.addAll(data)
        val fragments: MutableList<Fragment> = mutableListOf()
        // 遍历列表
        data.forEachIndexed { index, _ ->
            when (index) {
                0 -> fragments.add(WormFragment.newInstance())
                1 -> fragments.add(FriendFragment.newInstance())
            }
        }
        mAdapter?.notifyDataSetChanged()
    }

    override fun mediaListError() {

    }


    companion object {

        @JvmStatic
        fun newInstance() = MediaFragment()
    }
}
